<template>
    <div ref="containerRef" class="detail">
        <div class="detail_header">
            <a-affix :target="(containerRef as HTMLElement)">
                <a-page-header title="内容管理" :subtitle="type === 'edit' ? '修改' : '新增'" @back="onBack">
                    <template #extra>
                        <a-button type="primary" @click="onReleased">
                            <template #icon>
                                <icon-save v-if="type === 'edit'" />
                                <icon-send v-else />
                            </template>
                            <template #default>
                                {{ type === 'edit' ? '保存' : '发布' }}
                            </template>
                        </a-button>
                    </template>
                </a-page-header>
            </a-affix>
        </div>
        <div class="detail_content" style="display: flex; flex-direction: column;">
            <a-form ref="formRef" :model="form" auto-label-width>
                <a-form-item label="标题" field="title" required>
                    <a-input v-model.trim="form.title" placeholder="请输入标题" allow-clear />
                </a-form-item>
                <a-form-item label="分类" field="categoryId" required>
                    <a-tree-select v-model="form.categoryId" placeholder="请选择分类" allow-clear :data="categoryList" />
                </a-form-item>
                <a-form-item label="简介">
                    <a-textarea v-model.trim="form.introduction" placeholder="请输入简介" allow-clear/>
                </a-form-item>
                <a-form-item label="封面">
                    <a-upload list-type="picture-card" :custom-request="handleUpload" :file-list="fileList"
                        image-preview></a-upload>
                </a-form-item>
            </a-form>
            <div style="flex: 1;">
                <AiEditor v-model="form.content" />
            </div>
        </div>
    </div>
</template>
  
<script setup lang="ts">
import { uploadFile } from '@/apis';
import { addContent, getContent, updateContent } from '@/apis/website/content';
import type GiForm from '@/components/GiForm';
import { useForm, type Options } from '@/hooks';
import { useCategory } from '@/hooks/app';
import { useTabsStore } from '@/stores';
import { Message, type RequestOption } from '@arco-design/web-vue';
import AiEditor from './components/edit/index.vue';


const containerRef = ref<HTMLElement | null>()
const tabsStore = useTabsStore()
const route = useRoute()
const formRef = ref<InstanceType<typeof GiForm>>()
const { id, type } = route.query
const { form, resetForm } = useForm({
    title: '',
    picture: '',
    content: '',
    status: 2,
    sort: 999
})
const options: Options = {
    form: { size: 'large' },
    grid: { cols: 2 },
    btns: { hide: true },
}

const { categoryList, getCategoryList } = useCategory()
if (!categoryList.value.length) {
    getCategoryList()
}


// 新增
const onAdd = () => {
    reset()
}

// 修改
const onUpdate = async (id: string) => {
    reset()
    const res = await getContent(id)
    Object.assign(form, res.data)

    if (res.data.picture.length) {
        fileList.value.push({
            uid: res.data.id,
            name: 'upload1.jpg',
            url: res.data.picture
        })
    }
}

//返回
const onBack = () => {
    tabsStore.closeCurrent(route.path)
}

// 重置
const reset = () => {
    formRef.value?.resetFields()
    resetForm()
}

const fileList = ref([] as any)
//上传图片
const handleUpload = (options: RequestOption) => {
    const controller = new AbortController()
        ; (async function requestWrap() {
            const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
            onProgress(20)
            const formData = new FormData()
            formData.append(name as string, fileItem.file as Blob)
            try {
                const res = await uploadFile(formData)
                Message.success('上传成功')
                fileList.value.push({
                    uid: '-1',
                    name: 'upload1.jpg',
                    url: res.data.url
                })
                onSuccess(res)
                //search()
            } catch (error) {
                onError(error)
            }
        })()
    return {
        abort() {
            controller.abort()
        },
    }
}

//发布
const onReleased = async () => {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) return false
    try {
        if (type === 'edit') {
            if (fileList.value.length) {
                form.picture = fileList.value[0].url
            }

            await updateContent(form, id as string)
            Message.success('修改成功')
        } else {
            if (fileList.value.length) {
                form.picture = fileList.value[0].url
            }

            await addContent(form)
            Message.success('新增成功')
        }
        onBack()
        return true
    } catch (error) {
        console.error(error)
        return false
    }
}
onMounted(() => {
    // 当id存在与type为edit时，执行修改操作
    if (id && type === 'edit') {
        onUpdate(id as string)
    }
})
</script>
  
<style scoped lang="less"></style>
  